package sword.chapter2Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 题6的加强版
 * 双指针反向：排序数组中两数之和
 * 双指针同向：正整数中子数组的和或乘积
 *
 * @author K
 * @date 2021-10-31 21:04
 */
public class S7ThreeSum {
    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = threeSum(nums);
        System.out.println();
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int i = 0;
        while (i < nums.length - 2) {
            twoSum(nums, i, result);
            int t = nums[i];
            while (t == nums[i] && i < nums.length) {
                i++;
            }
        }
        return result;
    }

    public static void twoSum(int[] nums, int i, List<List<Integer>> result) {
        int start = i + 1;
        int end = nums.length - 1;
        while (start < end) {
            if (nums[i] + nums[start] + nums[end] == 0) {
                result.add(Arrays.asList(nums[i], nums[start], nums[end]));
                int t = nums[start];
                while (t == nums[start] && i < end) {
                    start++;
                }
            } else if (nums[i] + nums[start] + nums[end] > 0) {
                end--;
            } else {
                start++;
            }
        }
    }
}
